package com.qn.controller;

import cn.hutool.core.collection.CollUtil;
import com.qn.enums.ProcessInstanceStatusEnum;
import com.qn.result.BaseResponse;
import com.qn.vo.BpmTaskApproveReqVO;
import com.qn.vo.BpmTaskRejectReqVO;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.dromara.warm.flow.core.dto.FlowParams;
import org.dromara.warm.flow.core.entity.HisTask;
import org.dromara.warm.flow.core.entity.Task;
import org.dromara.warm.flow.core.entity.User;
import org.dromara.warm.flow.core.orm.agent.WarmQuery;
import org.dromara.warm.flow.core.service.HisTaskService;
import org.dromara.warm.flow.core.service.TaskService;
import org.dromara.warm.flow.core.service.UserService;
import org.dromara.warm.flow.core.utils.page.Page;
import org.dromara.warm.flow.orm.entity.FlowHisTask;
import org.dromara.warm.flow.orm.entity.FlowUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController("/task")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TaskController {

    public final String TASK_VARIABLE_REASON = "TASK_REASON";
    private final TaskService taskService;
    private final UserService userService;
    private final HisTaskService hisTaskService;

    /**
     * 完成节点任务.
     *
     * @return 流程key
     */
    @PostMapping("/complete")
    public ResponseEntity<Object> completeTask(@Valid @RequestBody BpmTaskApproveReqVO reqVO) {
        //1.完成指定任务的审批
        taskService.pass(reqVO.getId(), reqVO.getReason(), reqVO.getVariables(), ProcessInstanceStatusEnum.RUNNING.name(), ProcessInstanceStatusEnum.APPROVE.name());

        //2.返回响应
        return new ResponseEntity<>(new BaseResponse<>(null), HttpStatus.OK);
    }

    @PutMapping("/reject")
    @Operation(summary = "不通过任务")
    public ResponseEntity<BaseResponse> rejectTask(@Valid @RequestBody BpmTaskRejectReqVO reqVO) {
        FlowParams flowParams = FlowParams.build()
                .variable(reqVO.getVariables())
                .message(reqVO.getReason())
                .flowStatus(ProcessInstanceStatusEnum.REJECT.name())
                .hisStatus(ProcessInstanceStatusEnum.REJECT.name());
        taskService.rejectLastByInsId(reqVO.getInstanceId(), flowParams);

        return new ResponseEntity<>(new BaseResponse<>(true), HttpStatus.OK);
    }

    /**
     * 查询指定用户的待办任务列表
     */
    @GetMapping("/todo/list/{userId}")
    public ResponseEntity<BaseResponse<List<Map<String, Object>>>> getTodoTaskList(@PathVariable String userId) {
        //待办任务集合（带分页）
        FlowUser flowUser = new FlowUser();
        flowUser.setProcessedBy(userId);
        List<User> userList = new WarmQuery<>(userService)
                .list(flowUser);

        if (CollUtil.isEmpty(userList)) {
            return new ResponseEntity<>(new BaseResponse<>(CollUtil.newArrayList()), HttpStatus.OK);
        }

        List<Long> taskIds = userList.stream()
                .map(User::getAssociated)
                .filter(Objects::nonNull)
                .toList();
        List<Task> list = taskService.getByIds(taskIds);

        List<Map<String, Object>> result = list.stream().map(task -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", task.getId());
            map.put("name", task.getFlowName());
            map.put("assignee", task.getUserList());
            map.put("createTime", task.getCreateTime());
            map.put("processInstanceId", task.getInstanceId());
            map.put("processDefinitionId", task.getDefinitionId());
            return map;
        }).toList();
        return new ResponseEntity<>(new BaseResponse<>(result), HttpStatus.OK);
    }

    @GetMapping("done-page/{userId}")
    @Operation(summary = "获取 Done 已办任务分页")
    public ResponseEntity<BaseResponse<List<Map<String, Object>>>> getTaskDonePage(@PathVariable String userId) {

        FlowHisTask flowHisTask = new FlowHisTask();
        flowHisTask.setApprover(userId);
        List<HisTask> list = new WarmQuery<>(hisTaskService)
                .orderByCreateTime()
                .desc()
                .page(flowHisTask, new Page<>(1, 10))
                .getList();

        List<Map<String, Object>> result = list.stream().map(task -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", task.getId());
            map.put("name", task.getFlowName());
            map.put("approver", task.getApprover());
            map.put("createTime", task.getCreateTime());
            map.put("processInstanceId", task.getInstanceId());
            map.put("processDefinitionId", task.getDefinitionId());
            map.put("reason", task.getMessage());
            return map;
        }).toList();
        return new ResponseEntity<>(new BaseResponse<>(result), HttpStatus.OK);
    }

}
